import React, { ChangeEvent, FC, useState } from "react";
import styles from "./EditHeader.module.scss";
import { useNavigate, useParams } from "react-router-dom";
import { Button, Typography, Space, Input, message } from "antd";
import { LeftOutlined, CheckOutlined, EditOutlined } from "@ant-design/icons";
import EditToolbar from "./EditToolbar";
import useGetPageInfo from "../../../hooks/useGetPageInfo";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import { changePageInfoTitle } from "../../../store/pageInfoReducer";
import { useDispatch } from "react-redux";
import { useRequest, useKeyPress, useDebounceEffect } from "ahooks";
import { updateQuestion } from "../../../utils/api";
const { Title } = Typography;

//拆分标题组件
const TitleComponent: FC = () => {
  const dispatch = useDispatch();
  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    const newTitle = event.target.value.trim();
    if (!newTitle) return;
    dispatch(changePageInfoTitle(newTitle));
  };

  const { title } = useGetPageInfo();
  const [editState, SetEditState] = useState(false);
  if (editState) {
    return (
      <Input
        value={title}
        onPressEnter={() => SetEditState(false)}
        onBlur={() => SetEditState(false)}
        onChange={handleChange}
      />
    );
  }

  return (
    <Space>
      <Title style={{ fontSize: "16px", lineHeight: "1", marginBottom: "0" }}>
        {title}
      </Title>
      <Button
        icon={<EditOutlined />}
        type="text"
        onClick={() => SetEditState(true)}
      ></Button>
    </Space>
  );
};
//拆分保存组件
const TitleSave: FC = () => {
  const { componentList = [] } = useGetComponentInfo();
  const page = useGetPageInfo();
  const { id } = useParams();

  const { loading, run: handleSave } = useRequest(
    async () => {
      if (!id) return;
      await updateQuestion(id, { ...page, componentList });
    },
    {
      manual: true,
    }
  );
  useKeyPress(["ctrl.s", "meta.s"], (event: KeyboardEvent) => {
    event.preventDefault();
    if (!loading) handleSave();
  });
  //自动保存(防抖)
  useDebounceEffect(
    () => {
      handleSave();
    },
    [componentList, page],
    {
      wait: 3000,
    }
  );
  return (
    <Button icon={<CheckOutlined />} onClick={handleSave} disabled={loading}>
      保存
    </Button>
  );
};
//拆分发布组件
const TitlePublish: FC = () => {
  const nav = useNavigate();
  const { componentList = [] } = useGetComponentInfo();
  const page = useGetPageInfo();
  const { id } = useParams();
  const { loading, run: handlePublish } = useRequest(
    async () => {
      if (!id) return;
      await updateQuestion(id, { ...page, componentList, isPublished: true });
    },
    {
      manual: true,
      onSuccess() {
        message.success("发布成功");
        nav(`/question/stat/${id}`);
      },
    }
  );
  return (
    <Button type="primary" onClick={handlePublish} disabled={loading}>
      发布
    </Button>
  );
};
//编辑页面Header
const EditHeader: FC = () => {
  const nav = useNavigate();
  return (
    <div className={styles["header-wrapper"]}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
              返回
            </Button>
            <TitleComponent />
          </Space>
        </div>
        <div className={styles.main}>
          <EditToolbar />
        </div>
        <div className={styles.right}>
          <Space>
            <TitleSave />
            <TitlePublish />
          </Space>
        </div>
      </div>
    </div>
  );
};

export default EditHeader;
